from django.shortcuts import render
from django.conf import settings  #如何导入自己的配置文件
from rest_framework.response import Response
from .utils import OAuthQQ,QQNetworkError
from rest_framework.viewsets import ViewSet
from rest_framework import status
from .models import OauthUser
from users.serializers import UserSerializer
from users.utils import UsernameMobileAuthBackend

# Create your views here.

class QQUserLogin(ViewSet):

    def url(self,request):

        qq = OAuthQQ(**settings.QQ_CONFIG)
        url = qq.url()
        return Response(url)

    def get_qq_user(self,request):

        code = request.query_params.get("code")
        state = request.query_params.get("state")
        if code is None:
            return Response({"detail":"失败"})
        qq = OAuthQQ(**settings.QQ_CONFIG)
        try:
            access_token = qq.access_token(code)
            openid = qq.open_id(access_token)
            print(openid,access_token)
        except QQNetworkError:
            return Response({"detail":"网络错误"},status = status.HTTP_500_INTERNAL_SERVER_ERROR)
        try:
            qq_user = OauthUser.objects.get(name=1,openid=openid)
            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(qq_user.user)
            qq_user.user.token = jwt_encode_handler(payload)
            seriliazer = UserSerializer(instance=qq_user.user)
            return Response(seriliazer.data)
        except OauthUser.DoesNotExist:
            print("被调用")
            return Response({
                "access_token": access_token,
                "openid": openid,
            })

    def qq_user_login(self,request):
        """网站用户和QQ进行绑定"""
        # 接收客户端提交
        username = request.data.get("username")
        password = request.data.get("password")
        # 单点调试
        # 查询用户是否存在
        ModelBackend = UsernameMobileAuthBackend()
        user = ModelBackend.authenticate(request, username, password)
        if user is None:
            return Response({"detail": "用户信息不存在或密码错误!"}, status=status.HTTP_400_BAD_REQUEST)
        else:
            """绑定账号和QQ"""
            return self._qq_user_bind(request, user)

    def qq_user_register(self, request):
        """游客注册账号和QQ进行绑定"""
        # 接收客户端提交
        nickname = request.data.get("nickname")
        phone = request.data.get("phone")
        password = request.data.get("password")
        sms_code = request.data.get("sms_code")

        serializers = UserSerializer(data={
            "nickname": nickname,
            "phone": phone,
            "password": password,
            "sms_code": sms_code,
        })

        serializers.is_valid(raise_exception=True)
        user = serializers.save()
        return self._qq_user_bind(request, user)

    def _qq_user_bind(self, request, user):
        """平台账号绑定QQ信息"""
        access_token = request.data.get("access_token")
        openid = request.data.get("openid")
        try:
            OauthUser.objects.create(
                user=user,
                openid=openid,
                name=1,
                access_token=access_token,
            )

            # 返回jwt登录状态
            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            user.token = jwt_encode_handler(payload)
            serializer = UserSerializer(instance=user)
            return Response(serializer.data)
        except:
            return Response({"detail": "绑定QQ账号失败!请联系客服工作人员!"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)